package com.wzh.musichome.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wzh.musichome.common.ConstantCode;
import com.wzh.musichome.common.ResponseTemplate;
import com.wzh.musichome.entity.dto.FrontUserLoginDTO;
import com.wzh.musichome.entity.dto.FrontUserUpdateDTO;
import com.wzh.musichome.entity.dto.FrontUserDTO;
import com.wzh.musichome.entity.pojo.FrontUser;
import com.wzh.musichome.service.FrontUserService;
import com.wzh.musichome.utils.EhCacheUtil;
import com.wzh.musichome.utils.FastdfsClientUtil;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 前端用户 前端控制器
 * </p>
 *
 * @author wzh
 * @since 2020-12-10
 */
@RestController
@RequestMapping("/consumer")
public class FrontUserController {

    @Autowired
    private FrontUserService frontUserService;



    @Autowired
    private FastdfsClientUtil fastdfsClientUtil;

    /**
     * 添加前端用户
     */
    @PostMapping("/add")
    public Object addConsumer(@RequestBody FrontUserDTO frontUserDTO) {

        String username = frontUserDTO.getUsername();
        String password = frontUserDTO.getPassword();


        if (username == null || username.equals("")) {
            return ResponseTemplate.getFailureResponse(ConstantCode.FAILURE_INSERT, "用户名不能为空");
        }

        QueryWrapper<FrontUser> wrapper = new QueryWrapper<>();
        wrapper.eq("username", username);
        FrontUser frontUser1 = frontUserService.getOne(wrapper);
        if (frontUser1 != null) {
            return ResponseTemplate.getFailureResponse(ConstantCode.FAILURE_INSERT, "用户名已经存在");
        }

        if (password == null || password.equals("")) {
            return ResponseTemplate.getFailureResponse(ConstantCode.FAILURE_INSERT, "密码不能为空");
        }

        //保存到前端用户的对象中
        FrontUser frontUser = new FrontUser();
        BeanUtils.copyProperties(frontUserDTO, frontUser);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");    //格式化规则
        Date date = frontUserDTO.getBirth();         //获得你要处理的时间 Date型
        String strDate = sdf.format(date); //格式化成yyyy-MM-dd格式的时间字符串
        Date newDate = null;
        try {
            newDate = sdf.parse(strDate);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        java.sql.Date birth = new java.sql.Date(newDate.getTime());//最后转换成 java.sql.Date类
        frontUser.setBirth(birth);

        boolean flag = frontUserService.save(frontUser);
        if (flag) {   //保存成功
            ResponseTemplate.ResultData data = ResponseTemplate.getSuccessResponse();
            data.setMsg("新增成功");
            return data;
        }
        return ResponseTemplate.getFailureResponse(ConstantCode.FAILURE_INSERT, "新增失败");
    }

    /**
     * 修改前端用户
     */
    @PostMapping("/update")
    public Object updateConsumer(@RequestBody FrontUserUpdateDTO frontUserUpdateDTO) {
        String username = frontUserUpdateDTO.getUsername();
        String password = frontUserUpdateDTO.getPassword();


        if (username == null || username.equals("")) {
            return ResponseTemplate.getFailureResponse(ConstantCode.FAILURE_INSERT, "用户名不能为空");
        }

        if (password == null || password.equals("")) {
            return ResponseTemplate.getFailureResponse(ConstantCode.FAILURE_INSERT, "密码不能为空");
        }

        //保存到前端用户的对象中
        FrontUser frontUser = frontUserService.getById(frontUserUpdateDTO.getId());
        BeanUtils.copyProperties(frontUserUpdateDTO, frontUser);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");    //格式化规则
        Date date = frontUserUpdateDTO.getBirth();         //获得你要处理的时间 Date型
        String strDate = sdf.format(date); //格式化成yyyy-MM-dd格式的时间字符串
        Date newDate = null;
        try {
            newDate = sdf.parse(strDate);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        java.sql.Date birth = new java.sql.Date(newDate.getTime());//最后转换成 java.sql.Date类
        frontUser.setBirth(birth);

        boolean flag = frontUserService.saveOrUpdate(frontUser);
        if (flag) {   //保存成功
            ResponseTemplate.ResultData data = ResponseTemplate.getSuccessResponse();
            data.setMsg("更新成功");
            return data;
        }
        return ResponseTemplate.getFailureResponse(ConstantCode.FAILURE_UPDATE, "修改失败");
    }


    /**
     * 删除前端用户
     */
    @GetMapping("/delete")
    public Object deleteConsumer(@RequestParam int id) {
        try {
            boolean b1 = frontUserService.removeById(id);
            if (b1) {
                ResponseTemplate.ResultData data = ResponseTemplate.getSuccessResponse();
                data.setMsg("删除成功");
                return data;
            }
            return ResponseTemplate.getFailureResponse(ConstantCode.FAILURE_DELETE, "删除失败" );
        } catch (Exception e) {
            return ResponseTemplate.getFailureResponse(ConstantCode.FAILURE_DELETE, "删除失败！！ 具体原因" + e.getMessage());
        }
    }

    /**
     * 根据主键查询整个对象
     */
    @GetMapping("/selectByPrimaryKey/{id}")
    public Object test(@PathVariable int id){
        try {
            FrontUser frontUser = frontUserService.getById(id);
            if (frontUser != null) {
                ResponseTemplate.ResultData data = ResponseTemplate.getSuccessResponse();
                data.setMsg("查询成功");
                data.setData(frontUser);
                return data;
            }
            return ResponseTemplate.getFailureResponse(ConstantCode.FAILURE_QUERY, "未找到对应用户");
        } catch (Exception e) {
            return ResponseTemplate.getFailureResponse(ConstantCode.FAILURE_QUERY, "查询失败！！ 具体原因" + e.getMessage());
        }
    }




    @GetMapping("/findByName")
    public Object findByName(@RequestParam String name){
        QueryWrapper<FrontUser> wrapper = new QueryWrapper<>();
        wrapper.like("username",name);
        ResponseTemplate.ResultData data = ResponseTemplate.getSuccessResponse();
        try {
            List<FrontUser> list = frontUserService.list(wrapper);
            if (list.size()>0){
                data.setMsg("查询成功");
                data.setData(list);
            }else {
                data.setFlag(false);
                data.setMsg("没有相关用户");
            }
            return data;
        } catch (Exception e) {
            return ResponseTemplate.getFailureResponse(ConstantCode.FAILURE_QUERY, "查询失败！！ 具体原因" + e.getMessage());
        }
    }
    /**
     * 查询所有前端用户
     */
    @GetMapping("/allConsumer")
    public Object allConsumer(@RequestParam(required = false) Long current, @RequestParam(required = false) Long size) {
        try {
            ResponseTemplate.ResultData data = ResponseTemplate.getSuccessResponse();
            data.setMsg("查询成功");
            if (current != null && size != null) {
                Page<FrontUser> page = new Page<>();
                page.setCurrent(current);
                page.setSize(size);
                Page<FrontUser> list = frontUserService.page(page);
                if (list.getTotal() != 0) {
                    data.setData(list);
                }
            } else {
                Object cacheList = EhCacheUtil.get("local", "user");
                if (cacheList != null) {
                    data.setData(cacheList);
                } else {
                    List<FrontUser> list = frontUserService.list();
                    data.setData(list);
                    EhCacheUtil.set("local", "user", list);
                }
            }
            return data;
        } catch (Exception e) {
            return ResponseTemplate.getFailureResponse(ConstantCode.FAILURE_QUERY, "查询失败！！ 具体原因" + e.getMessage());
        }
    }

//    /**
//     * 更新前端用户图片
//     */
//    @RequestMapping(value = "/updateConsumerPic",method = RequestMethod.POST)
//    public Object updateConsumerPic(@RequestParam("file") MultipartFile avatorFile, @RequestParam("id")int id){
//        JSONObject jsonObject = new JSONObject();
//        if(avatorFile.isEmpty()){
//            return ResponseTemplate.getFailureResponse(ConstantCode.FAILURE_UPLOAD, "图片上传失败");
//        }
//        //文件名=当前时间到毫秒+原来的文件名
//        String fileName = System.currentTimeMillis()+avatorFile.getOriginalFilename();
//        //文件路径
//        String filePath = System.getProperty("user.dir")+System.getProperty("file.separator")+"avatorImages";
//        //如果文件路径不存在，新增该路径
//        File file1 = new File(filePath);
//        if(!file1.exists()){
//            file1.mkdir();
//        }
//        //实际的文件地址
//        File dest = new File(filePath+System.getProperty("file.separator")+fileName);
//        //存储到数据库里的相对文件地址
//        String storeAvatorPath = "/avatorImages/"+fileName;
//        try {
//            avatorFile.transferTo(dest);
//            Consumer consumer = new Consumer();
//            consumer.setId(id);
//            consumer.setAvator(storeAvatorPath);
//            boolean flag = consumerService.saveOrUpdate(consumer);
//            if(flag){
//                ResponseTemplate.ResultData data = ResponseTemplate.getSuccessResponse();
//                data.setMsg("上传成功");
//                data.setData(storeAvatorPath);
//                return data;
//            }
//            return ResponseTemplate.getFailureResponse(ConstantCode.FAILURE_UPLOAD, "图片上传失败");
//        } catch (IOException e) {
//            return ResponseTemplate.getFailureResponse(ConstantCode.FAILURE_UPLOAD, "图片上传失败"+e.getMessage());
//        }
//    }


    /**
     * 更新前端用户图片
     */
    @PostMapping("/updateConsumerPic")
    public Object updateConsumerPic(@RequestParam("file") MultipartFile avatorFile, @RequestParam("id") int id) {
        try {
            FrontUser byId = frontUserService.getById(id);
            if (!byId.getAvator().equals(ConstantCode.defaultImgUrl)) {
                String[] split = byId.getAvator().split("\\.");
                String sltUrl = split[0] + "_60x60." + split[1];
                fastdfsClientUtil.deleteFile(byId.getAvator());
                fastdfsClientUtil.deleteFile(sltUrl);
            }
            String url = fastdfsClientUtil.upload(avatorFile);
            FrontUser frontUser = new FrontUser();
            frontUser.setId(id);
            frontUser.setAvator(url);
            boolean flag = frontUserService.saveOrUpdate(frontUser);
            if (flag) {
                ResponseTemplate.ResultData data = ResponseTemplate.getSuccessResponse();
                data.setMsg("头像更改成功");
                data.setData(url);
                return data;
            }
            return ResponseTemplate.getFailureResponse(ConstantCode.FAILURE_UPLOAD, "图片更改失败");
        } catch (IOException e) {
            return ResponseTemplate.getFailureResponse(ConstantCode.FAILURE_UPLOAD, "图片更改失败" + e.getMessage());
        } catch (Exception e) {
            return ResponseTemplate.getFailureResponse(ConstantCode.FAILURE_UPLOAD, "图片更改失败" + e.getMessage());
        }
    }


    @PostMapping("/upload")
    public Object upload(MultipartFile file) {
        try {
            String url = fastdfsClientUtil.upload(file);
            if (url != null) {
                ResponseTemplate.ResultData data = ResponseTemplate.getSuccessResponse();
                data.setData(url);
                data.setMsg("插入成功");
                return data;
            } else {
                return ResponseTemplate.getFailureResponse(ConstantCode.FAILURE_UPLOAD, "图片上传失败");
            }
        } catch (Exception e) {
            return ResponseTemplate.getFailureResponse(ConstantCode.FAILURE_UPLOAD, "图片上传失败" + e.getMessage());
        }
    }


//    /**
//     * 前端用户登录
//     */
//    @RequestMapping(value = "/login", method = RequestMethod.POST)
//    public Object login(@RequestBody ConsumerLoginDTO consumerLoginDTO, HttpSession session) {
//        String username = consumerLoginDTO.getUsername();
//        String password = consumerLoginDTO.getPassword();
//        //检测用户名和密码是否为空
//        if (StringUtils.isBlank(username) || StringUtils.isBlank(password)) {
//            return ResponseTemplate.getFailureResponse(ConstantCode.FAILURE_LOGIN_USERNAME_PASSWORD_EMPTY, "用户名/密码不能为空");
//        }
//        QueryWrapper<Consumer> wrapper = new QueryWrapper<>();
//        wrapper.eq("username", username);
//        Consumer consumer = consumerService.getOne(wrapper);
//        if (consumer == null) {
//            return ResponseTemplate.getFailureResponse(ConstantCode.FAILURE_LOGIN_USER_NULL, "用户不存在");
//        }
//        if (!password.matches(consumer.getPassword())) {
//            return ResponseTemplate.getFailureResponse(ConstantCode.FAILURE_LOGIN_PASSWORD_WRONG, "密码错误");
//        }
//        ResponseTemplate.ResultData data = ResponseTemplate.getSuccessResponse();
//        data.setMsg("登录成功");
//        data.setData(consumer);
//        session.setAttribute("username", username);
//        return data;
//    }


    /**
     * 前端用户登录
     */
    @PostMapping("/login")
    public Object login(@RequestBody FrontUserLoginDTO frontUserLoginDTO) {
        String username = frontUserLoginDTO.getUsername();
        String password = frontUserLoginDTO.getPassword();
        //检测用户名和密码是否为空
        if (StringUtils.isBlank(username) || StringUtils.isBlank(password)) {
            return ResponseTemplate.getFailureResponse(ConstantCode.FAILURE_LOGIN_USERNAME_PASSWORD_EMPTY, "用户名/密码不能为空");
        }
        QueryWrapper<FrontUser> wrapper = new QueryWrapper<>();
        wrapper.eq("username", username);
        FrontUser frontUser = frontUserService.getOne(wrapper);
        if (frontUser == null) {
            return ResponseTemplate.getFailureResponse(ConstantCode.FAILURE_LOGIN_USER_NULL, "用户不存在");
        }
        if (!password.matches(frontUser.getPassword())) {
            return ResponseTemplate.getFailureResponse(ConstantCode.FAILURE_LOGIN_PASSWORD_WRONG, "密码错误");
        }
        return frontUserService.login(frontUserLoginDTO);
    }

    @GetMapping("/info")
    public Object getConsumerInfo(@RequestParam String token){
        try {
            return frontUserService.getConsumerInfo(token);
        } catch (Exception e) {
            return ResponseTemplate.getFailureResponse(ConstantCode.FAILURE_LOGIN_TOKEN_FAILURE, e.getMessage());
        }
    }

    @ApiOperation(value = "退出")
    @PostMapping("/logout")
    public Object logout(){
        ResponseTemplate.ResultData data = ResponseTemplate.getSuccessResponse();
        data.setMsg("退出成功");
        return data ;
    }


}
